package com.hp.bon.sgw.wkflow.impl;

import java.util.Map;

import org.dom4j.Element;

import com.hp.bon.sgw.bean.ProtocalConvertResult;
import com.hp.bon.sgw.convert.DataExchangerImpl;
import com.hp.bon.sgw.domain.ConvMapInfo;
import com.hp.bon.sgw.util.dcc.DccAvpHelper;
import com.hp.bon.sgw.wkflow.FlowVarObj;
import com.hp.ocs.diameter.message.AVP;
import com.hp.ocs.diameter.message.Message;

/**
 * 实现将AVP 完整转换为为XML数据的字符串 用法：${comAVP2XML.repsMsg.Service_Information/xxxx/yyy}
 * 
 * @author wuzhih
 * 
 */
public class AVP2XMLConvertVarObj extends FlowVarObj {

	private final DataExchangerImpl bonServiceDataExchanger;

	public AVP2XMLConvertVarObj(
			DataExchangerImpl bonServiceDataExchanger) {
		this.bonServiceDataExchanger = bonServiceDataExchanger;
	}

	@Override
	public Object getProperty(String express) {
		String[] items = express.split("\\.");
		String dccMsgName = items[0];
		String avpName = items[1];
		StringBuilder leafAVPName = new StringBuilder();
		DCCMsgVarObj dccMsgVar = (DCCMsgVarObj) this.flowExprParser
				.getVar(dccMsgName);
		if (dccMsgVar == null) {
			throw new RuntimeException("can't find dcc message of name :"
					+ dccMsgName);
		}
		Message dccMsg = dccMsgVar.getMessage();
		Map<String, ConvMapInfo> avpMaping = dccMsgVar.getAllAVPNamesMap();
		
		if (dccMsg == null) {			
			return null;
		}
		AVP avp = DccAvpHelper.getAVP(dccMsg, avpName, avpMaping, leafAVPName);
		if (avp != null) {
			ProtocalConvertResult<Element> convertRst = bonServiceDataExchanger
					.transtoXML(dccMsgVar.getAllAvpCodeMap(), avp);
			if (convertRst.getRetCode() != 0) {
				throw new RuntimeException("convert avp err:"
						+ convertRst.getErrMsg());
			} else {
				return convertRst.getResult().asXML();
			}
		}
		return null;

	}

}
